<template>
  <app-dialog v-model="show" width="1000px" style="top: 3vh" :title="parentdata.label" @open="handleOpen">
    <el-form ref="formRef" :model="formData" :inline="true" label-width="100px" label-position="right"
      style="width: 70%; margin: 0 auto">
      <app-form-group v-model="formData" :json="formJson" />

    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" class="hovepcvicecolor" @click="handleSubmit">确定</el-button>
    </template>
  </app-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { getPlatform } from '@/api'
import { http } from '@/utils/http'
import { http as httpuc } from '@/utils/uc-http'
import { checkRoles } from '@/stores/roles'
const show = defineModel({ type: Boolean })
const emits = defineEmits(['change'])
const props = defineProps({
  data: Object,
  parentdata: Object,
})

const userStore = useUserStore()
const options = reactive({
  userTypes: [
    { value: 1, label: '代理' },
    { value: 0, label: '平台' },
  ],
  groups: [],
  status: [
    { value: 0, label: '准备-0' },
    { value: 1, label: '开启-1' },
    { value: 2, label: '暂停-2' },
    { value: 3, label: '关闭-3' },
  ],
  ips: [],
  agents: [],
  platforms: [],

  sources: [],
  moneyCodes: [],

  loginRules: [],
})

const formRef = ref(null)
const formData = ref({
  place_order_stakes: [],
})

const required = true
const formJson = computed(() => {
  let json = [
    {
      name: 'user_name',
      label: '用户',
      required,
      span: 12,
      inputAttr: {
        style: 'width:240px',
        disabled: props.parentdata.status == 'update',
      },
    },
    {
      name: 'pass_word',
      label: '密码',
      span: 12,
      required,
      inputAttr: {
        style: 'width:240px',
      },
    },
    {
      name: 'amount',
      label: '账面金额',
      required,
      type: 'input-number',
      span: 12,
      inputAttr: {
        'controls-position': 'right',
        style: 'width:240px',
        disabled: props.parentdata.status == 'update' && formData.value.user_type == 1,
      },
    },
    ...(() => {
      const json = []
      if (props.parentdata.status == 'create') {
        json.push({
          name: 'is_init',
          label: '分类',
          required,
          type: 'select',
          span: 12,
          options: [
            { value: 0, label: '已修改账号密码' },
            { value: 1, label: '未修改账号密码' },
          ],
          inputAttr: {
            style: 'width:240px',
          },
        })
      }
      return json
    })(),
    ...(() => {
      const json = []
      if (props.parentdata.status == 'create' && formData.value.is_init == 1) {
        json.push(
          {
            name: 'init_username',
            label: '新用户名',
            required,
            span: 12,
            inputAttr: {
              style: 'width:240px',
            },
          },
          {
            name: 'init_password',
            label: '新密码',
            required,
            span: 12,
            inputAttr: {
              style: 'width:240px',
            },
          }
        )
      }
      return json
    })(),
    {
      name: 'group_id',
      label: '所属分组',
      required,
      type: 'select',
      span: 12,
      options: options.groups,
      inputAttr: {
        style: 'width:240px',
        // onChange(value) {
        //   getAgent()
        // },
      },
    },
    {
      name: 'bc_type',
      label: '所属平台',
      required,
      type: 'select',
      span: 12,
      options: options.platforms,
      inputAttr: {
        style: 'width:240px',
        onChange: () => {
          getFeesIp()
        },
        disabled: props.parentdata.status == 'update',
      },
    },

    {
      name: 'sport_type',
      label: '玩法类型',
      type: 'select',
      span: 12,
      options: [
        { value: 'all', label: '不限' },
        { value: 'soccer', label: '足球' },
        { value: 'basketball', label: '篮球' },
      ],
      inputAttr: {
        style: 'width:240px',
      },
    },

    {
      name: 'stop_amount',
      label: '止盈金额',
      type: 'number',
      span: 12,
      inputAttr: {
        style: 'width:240px',
      },
    },

    // {
    //   name: 'proxy_ip_id',
    //   label: '代理IP',
    //   required,
    //   type: 'select',
    //   span: 12,
    //   options: options.ips,
    //   inputAttr: {
    //     style: 'width:240px',
    //   },
    // },
    {
      name: 'fees_type',
      label: 'IP类型',
      required,
      type: 'select',
      span: 12,
      options: [
        { value: 'free', label: '共享', disabled: !checkRoles(userStore.user.roles, 'share') },
        { value: 'fees', label: '独享' }
      ],
      inputAttr: {
        style: 'width:240px',
        onChange: () => {
          getFeesIp()
        },
      },
    },
    ...(() => {
      const json = []
      if (props.parentdata.status == 'create' && formData.value.fees_type == 'free') {
        json.push(
          {
            name: 'region',
            label: '地区',
            required,
            type: 'select',
            span: 12,
            options: options.ipregions,
            inputAttr: {
              style: 'width:240px',
              onChange: () => {
                getFeesIp2()
              },
            },
          },
        )
      }
      return json
    })(),
    {
      name: 'login_rule_id',
      label: '登录规则ID',
      required,
      type: 'select',
      span: 12,
      options: options.loginRules,
      inputAttr: {
        style: 'width:240px',
      },
    },
    {
      name: 'status',
      label: '状态',
      required,
      type: 'select',
      span: 12,
      options: options.status,
      inputAttr: {
        style: 'width:240px',
      },
    },

    {
      name: 'percent',
      label: '成数',
      required,
      type: 'number',
      span: 12,
      inputAttr: {
        style: 'width:240px',
      },
    },
    {
      name: 'share_rate',
      label: '共享费率',
      // required,
      type: 'number',
      span: 12,
      inputAttr: {
        style: 'width:240px',
        prefix: '12',
      },
    },
    {
      name: 'money_code',
      label: '货币',
      type: 'select',
      options: options.moneyCodes,
      required,
      span: 12,
      inputAttr: {
        style: 'width:240px',
      },
    },
    {
      name: 'source_id',
      label: '来源',
      type: 'select',
      options: options.sources,
      required,
      span: 12,
      inputAttr: {
        style: 'width:240px',
      },
    },
    {
      name: 'remark',
      label: '备注',
      type: 'textarea',
      span: 24,
      inputAttr: {
        style: 'width:570px',
      },
    },

    ...(() => {
      let json = []

      if (formData.value.user_type == 0) {
        json = json.concat([])
      }

      return json
    })(),
  ]

  return json
})

const handleOpen = async () => {
  formData.value = {
    amount: 0,
    remark: '',
    ...props.data,
  }


  if (props.parentdata.status == 'update') {
    let a = JSON.parse(JSON.stringify(props.data))
    // getGroupList(props.data.user_type)
    // getAgent()
    // getIpList(formData.value.bc_type, 0)
    formData.value = {
      status: a.status,
      id: a.id,
      login_rule_id: a.login_rule?.id,
      group_id: a.group.id,
      source_id: a.source.id,
      money_code: a.money?.money_code,
      proxy_ip_id: a.proxy_ip?.id,
      user_name: a.user_name,
      pass_word: a.pass_word,
      percent: a.percent,
      remark: a.remark,
      bc_type: a.bc_type,
      amount: a.amount,
      place_league: a.place_league,
      place_pk_key_amount: a.place_pk_key_amount,
      no_place_pk_key: a.no_place_pk_key,
      no_place_pk_type: a.no_place_pk_type,
      place_order_stakes: a.place_order_stakes,
      login_status: a.login_status,
      sport_type: a.sport_type,
      stop_amount: a.stop_amount,
      share_rate: a.share_rate
    }

    if (props.data.proxy_ip.fees_type && props.data.proxy_ip.fees_type == 'free') {
      formData.value.fees_type = 'free'
    } else {
      formData.value.fees_type = 'fees'
    }
  } else {
    formData.value.share_rate = 0
  }



  // 获取登录规则
  http.get('/loginrule/loginrule_list', { params: { page: 1, page_size: 999 } }).then(res => {
    options.loginRules = res.data.list.map(item => {
      return { value: item.id, label: item.name }
    })
  })

  // 获取来源列表
  http.get('/source/source_list', { params: { page: 1, page_size: 999 } }).then(res => {
    options.sources = res.data.list.map(item => {
      return { value: item.id, label: item.name }
    })
  })

  // UC代理IP支持区域
  httpuc.get('/api_ip_regions').then(res => {
    options.ipregions = res.map(item => {
      return { value: item.code, label: item.name_zh }
    })
  })

  // platforms
  // 获取平台列表
  // http.get('/config/get_bc_type', { params: { page: 1, page_size: 999 } }).then(res => {
  //   options.platforms = res.data.out_platform.map(item => {
  //     return { value: item.bc_type, label: item.name }
  //   })
  // })
  options.platforms = userStore.user.subscribe[`${userStore.user.plant_code}:data_api`].selected.map(item => {
    return { value: item.value, label: item.name }
  })
  // 获取分组列表
  http.get('/group/group_list', { params: { page: 1, page_size: 999 } }).then(res => {
    options.groups = res.data.list.map(item => {
      return { value: item.id, label: item.name }
    })
  })

  // 获取货币
  http.get('/money/money_list', { params: { page: 1, page_size: 999 } }).then(res => {
    options.moneyCodes = res.data.list.map(item => {
      return { value: item.money_code, label: item.money_code + '(' + item.exchange_rate + ')' }
    })
  })
}

const handleClose = () => {
  show.value = false
}

const handleSubmit = () => {
  formRef.value.validate().then(async () => {
    const body = {
      ...formData.value,
    }
    // if (body.user_type == 1) {
    //   const agent = options.agents.find(item => item.value == body.agent_id)
    //   body.bc_type = agent.bc_type
    //   body.source_id = ''
    //   body.money_code = ''
    //   body.percent = ''
    // } else {
    //   body.agent_id = ''
    // }
    // body.proxy_ip_id = 298
    if (body.region) {
      delete body.region
    }

    // if (formData.value.proxy_ip_id == null || formData.value.proxy_ip_id == undefined) {
    //   ElMessage({
    //     message: '暂无可用IP',
    //     type: 'warning',
    //   })
    //   return
    // }

    delete body.fees_type

    // body.proxy_ip_id = 411
    const onSuccess = () => {
      ElMessage.success('操作成功')
      handleClose()
      emits('change')
    }
    body.amount = body.amount.toString()
    console.log(body);

    if (body.id) {
      http({
        method: 'POST',
        url: '/member/member_update',
        data: body,
      }).then(onSuccess)
    } else {
      http({
        method: 'POST',
        url: '/member/member_create',
        data: body,
      }).then(onSuccess)
    }
  })
}

const getFeesIp = () => {
  if (formData.value.fees_type != undefined && formData.value.fees_type == 'fees' && formData.value.bc_type != undefined) {
    let body = {
      bc_type: formData.value.bc_type,
      fees_type: formData.value.fees_type
    }
    http.get('/proxyip/proxyip_usable', { params: body }).then((res) => {
      if (res.data.id != null && res.data.id != undefined) {
        formData.value.proxy_ip_id = res.data.id
      } else {
        ElMessage({
          message: '暂无可用IP',
          type: 'warning',
        })
      }

    })
  }
}

const getFeesIp2 = () => {
  // if (formData.value.fees_type != undefined && formData.value.fees_type == 'fees' && formData.value.bc_type != undefined) {
  let body = {
    bc_type: formData.value.bc_type,
    fees_type: formData.value.fees_type,
    region: formData.value.region
  }
  http.get('/proxyip/proxyip_usable', { params: body }).then((res) => {
    if (res.data.id != null && res.data.id != undefined) {
      formData.value.proxy_ip_id = res.data.id
    } else {
      ElMessage({
        message: '暂无可用IP',
        type: 'warning',
      })
    }

  })
  // }
}

function getIpList(bc_typeTow, type) {
  if (!bc_typeTow) return

  const params = { page: 1, page_size: 100 }
  const agent = options.agents.find(item => item.value == formData.value.agent_id)
  let bc_type = type == 1 ? agent.bc_type : bc_typeTow
  const parts = bc_type.split('_')
  const result = parts.length > 1 ? parts[1] : parts[0]
  let bctypestr = ''
  if (result.includes('hga')) {
    bctypestr = 'hga'
  } else {
    bctypestr = result
  }
  // 代理
  if (type == 1) {
    formData.value.proxy_ip = null

    http.get('/proxyip/proxyip_list_by_bc_type', { params: { ...params, bc_type: bctypestr } }).then(res => {
      options.ips = res.data.list.map(item => {
        return { value: item.id, label: item.ip }
      })
    })
  } else {
    http.get('/proxyip/proxyip_list_by_bc_type', { params: { ...params, bc_type: bctypestr } }).then(res => {
      let a = res.data.list.map(item => {
        return { value: item.id, label: item.ip }
      })
      if (props.parentdata.status == 'update') {
        let b = [{ value: formData.value.proxy_ip, label: formData.value.proxy_ip }]
        a.unshift(...b) // 在数组头部添加对象 b
        options.ips = a
      }
      options.ips = a
    })
  }
}

function getGroupList(value) {
  http
    .get('/group/list', {
      params: {
        types: value === 0 ? '5,6,7,8' : '1,2,3,4',
        page: 1,
        page_size: 100,
      },
    })
    .then(res => {
      options.groups = []
      options.groups = res.data.list.map(item => {
        return { value: item.id, label: item.name }
      })
    })
}

function getAgent() {
  const value = formData.value.group_id
  const params = { page: 1, page_size: 100 }
  if (formData.value.user_type == 0) {
    getPlatform({ ...params, category: 'user' }).then(res => {
      options.platforms = res.data.map(item => {
        return { value: item.bc_type ?? item.id, label: item.name, disabled: !item.is_active }
      })
    })
  } else {
    http
      .get('/agent/list', {
        params: { ...params, group_id: value },
      })
      .then(res => {
        options.agents = res.data.list.map(item => {
          return { ...item, value: item.id, label: item.user_name }
        })
      })
  }
}
</script>
<style lang="scss" scoped></style>